package com.yangda.example.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import com.yangda.example.framework.ResultCode;
import com.yangda.example.framework.exception.BizException;
import com.yangda.example.framework.model.Pagination;

public class BaseController<T> {
	private final static String TOKEN = "token";
	public final static String SUCCESS ="success";
	public final static String ERROR ="error";
	public final static String FAIL ="fail";

	/*
	 * @Autowired private IBaseService<T> baseService;
	 */
 
	//设置token
	public String setToken(HttpServletRequest request) {
		String uuid = UUID.randomUUID().toString();
		request.setAttribute(TOKEN, uuid);
		request.getSession().setAttribute(TOKEN+uuid,uuid);
		return uuid;
	}

	//验证token成功返回true 并移除token  失败返回false
	public void isTokenValid(HttpServletRequest request) {
		String client_token = request.getParameter(TOKEN);
		
		ResultCode resultCode = ResultCode.TOKEN_ERROR;
		if (client_token == null) {//前台令牌值为空 验证不通过
			throw new BizException(resultCode.getCode(), resultCode.getMessage());
		}
		String server_token_name = TOKEN + client_token; //后台令牌名
		
		String server_token = (String) request.getSession().getAttribute(server_token_name);
		if (server_token == null) {//后台令牌为空 验证不通过
			throw new BizException(resultCode.getCode(), resultCode.getMessage());
		}
		if (!client_token.equals(server_token)) {//后台令牌和前台令牌不相同
			throw new BizException(resultCode.getCode(), resultCode.getMessage());
		}
		request.getSession().removeAttribute(server_token_name);
	}
	
	/**
	 * 获取bootstrap-table表格分页数据
	 * @return map对象
	 */
	public <T> Map<String, Object> getBootstrapTableData(Pagination<T> result){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", result.getResult());
		map.put("total", result.getTotalCount());
		return map;
	}
	
	public <T> Map<String, Object> getBootstrapTableData(List<T> result){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rows", result);
		map.put("total", result==null ? 0 : result.size());
		return map;
	}

}
